require('js/lib/require_patch').monkeypatch(this); // Needed for Android

/**
 * @author Mark Rosenthal
 */
var ui = require('js/ui/common/ui');  

exports.PatientSelectorWin = function(params) {
	var CHAR_COUNT = 2;
	var patientWin = ui.window('Patient Selection',{backgroundColor: '#000'});
	//SEARCH BAR
	var search = Titanium.UI.createSearchBar({
	   barColor:'#77B121',
	   height:50 * globals.deviceFactor,
	   hintText:'Patient Name?',
	   top: 0
	});
	patientWin.addChild(search);
		
	// New Patient control
	var newPatientBtn = ui.button({
		backgroundImage: globals.util.urls()['add'],
		width: '25', 
		height: '25',
		top:10, right: 5
	}, function(){
		createNewPatientWindow().open();
	});
	patientWin.addHeaderChild(newPatientBtn);
	 
	//AUTOCOMPLETE TABLE
	var table_data = [];
	var autocomplete_table = Titanium.UI.createTableView({
		headerText: 'Select a Patient',
	   	searchHidden: false,
	   	scrollable: true,
	   	top:50 * globals.deviceFactor
	});
	patientWin.addChild(autocomplete_table);
	 
	//
	// SEARCH BAR EVENTS
	//
	var last_search = null;
	search.addEventListener('change', function(e)
	{
	   if (search.value.length >= CHAR_COUNT && search.value != last_search)
	   {
	   		if (globals.timers['autocomplete'])
	      		clearTimeout(globals.timers['autocomplete']);
			globals.timers['autocomplete'] = setTimeout(function()
			{
				last_search = search.value;
				auto_complete(search.value, CHAR_COUNT, autocomplete_table);
			}, 300);
		}
	   	return false;
	});
	 
	patientWin.addEventListener('focus', function(e){
		search.focus();
	});
	 
	patientWin.addEventListener('blur', function(e){
		search.blur();
	});
	patientWin.addEventListener('close', function(e){
		search.blur();
	});

	autocomplete_table.addEventListener('click', function(e){
		globals.patient = e.rowData;
		Ti.App.fireEvent('app.patient.change', {});
		search.blur();
		
		// Select appointment
		var today = globals.db.timeStamp().substr(0,10);
		var appts = globals.db.listPatientAppointments('date(date) = ? AND patient_id = ?', [ today, globals.patient.id] );
		if (appts.length > 0) {
			globals.appointment = appts[0];
		}
		else {
			var PatientAppointment = require('js/model/PatientAppointment');
			var date = globals.db.timeStamp();
			var appt = new PatientAppointment({date: date, patient_id: globals.patient.id, type: null});
			globals.db.addPatientAppointment(appt);
			var appts = globals.db.listPatientAppointments('date(date) = ? AND patient_id = ?', [ today, globals.patient.id] );
			if (appts.length > 0) {
				globals.appointment = appts[0];
			}
		}
		if (globals.appointment) {
			Ti.App.fireEvent('app.appointment.change', {appointment:globals.appointment});
		}
		
		patientWin.close();
		Ti.API.debug("Resuming app.js processing...");
		params.selected(e);
	});

	return patientWin;
	
	function createNewPatientWindow(args) {    
	    var win = ui.window('Create Patient');
	//    ui.addBackButtonView(win);
	 
	    var webview = Ti.UI.createWebView({
	        url:'html/addPatientForm.html',
	        backgroundColor:'#787878'
	    });
	    win.addChild(webview);
	    	 
	    //listen for events coming from the web view to save data...
	    Ti.App.addEventListener('patientSaved', function(e) {
	        var Patient = require('js/model/Patient');
	        var patient = new Patient(e);
	    	Ti.API.debug('Saving patient ' + patient.fullName());
	        globals.db.addPatient(patient);
	        win.close();
	        
	        autocomplete_table.fireEvent('click',{ rowData: createPatientRow(patient) });
	    });
		Ti.App.addEventListener('patientSaveCancelled', function(e) {
	    	Ti.API.debug('Cancel Saving patient ');
	        win.close();
	    });
		win.addEventListener('close', function(e){
			Ti.API.debug('Removing app listeners ');
			Ti.App.removeEventListener('patientSaved', function(e){});
			Ti.App.removeEventListener('patientSaveCancelled', function(e){});
		});
	     
	    return win;
	};
	
	
    Ti.App.addEventListener('app:databaseUpdated', function(e){
    	Ti.API.debug(' +++ Setting selected patient to: ' + e.patient.title);
    	autocomplete_table.setData([createPatientRow(e.patient)]);
    	Ti.App.removeEventListener('app:databaseUpdated');
    });

}

function auto_complete(search_term, trigger, table)
{
   if (search_term.length >= trigger)
   {
   	
   	// TODO: Implement Ajax functionality.  For now, use a local database
   		var table_data = [];
   		var rows = globals.db.listPatients('first_name LIKE "%' + search_term+ '%" OR last_name LIKE "%'+ search_term + '%"');

		for (var i=0, l=rows.length; i<l; i++) {
            table_data.push(createPatientRow (rows[i]));
		}

//      var url = 'AJAXURL' + escape( search_term);
//      var ajax_cache_domain = 'autocomplete';
//      var params = {};
//      var cache_for = '+7 days';
//      ajax.get(url, params, ajax_cache_domain, cache_for, function (response)
//      {
//         if (typeof(response) == 'object')
//         {
//            var list = response;
            // Empty array &quot;data&quot; for our tableview
//            table_data = [];
 
//            for (var i = 0; i < list.length; i++)
//            {
               //Ti.API.info('row data - ' + data[i].value);
//               var row = Ti.UI.createTableViewRow(
//               {
//                  height: 40 * globals.deviceFactor,
//                  title: list[i].value.replace(/^\s+|\s+$/g,""),
//                  hasDetail:true
//               });
 
               // apply rows to data array
//               table_data.push(row);
 
//            };
 
            // set data into tableView
 
           table.setData(table_data);
//           search.value = search.value;
//         }
//         else
//         {
//            alert(response.error);
//         }
 
//      });
   }
}

function createPatientRow (patient) {
	var row = Ti.UI.createTableViewRow({
		height: 40 * globals.deviceFactor
    });
   
	return	globals.util.objectMerge(row, patient);
}